package timeutil

import (
	"errors"
	"time"
)

// GeneratorYesterdayPeriod 生成昨日时间区间
// 2006-01-02 00:00:00 ----- 2006-01-03 00:00:00
func GeneratorYesterdayPeriod() (time.Time, time.Time) {
	now := time.Now().In(time.UTC)
	begin := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, now.Location())
	end := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	return begin, end
}

type TimeInterval struct {
	Begin time.Time
	End   time.Time
}

// TimeProcessInterval 时间处理成时间区间
func TimeProcessInterval(t ...time.Time) []TimeInterval {
	tis := make([]TimeInterval, 0)
	for _, v := range t {
		tm1 := time.Date(v.Year(), v.Month(), v.Day(), 0, 0, 0, 0, v.Location())
		tm2 := tm1.AddDate(0, 0, 1)
		ti := TimeInterval{
			Begin: tm1,
			End:   tm2,
		}
		tis = append(tis, ti)
	}
	return tis
}

func TimeProcessReportParams(style string, ti []string) ([]time.Time, error) {
	if style != "day" && style != "week" && style != "month" {
		return nil, errors.New("unsupported_metric_calculation")
	}
	if len(ti) != 2 {
		return nil, errors.New("date_format_error")
	}
	beginStr := ti[0]
	beginTime, err := time.Parse("2006-01-02", beginStr)
	if err != nil {
		return nil, errors.New("date_format_error")
	}
	endStr := ti[1]
	endTime, err := time.Parse("2006-01-02", endStr)
	if err != nil {
		return nil, errors.New("date_format_error")
	}
	if endTime.Before(beginTime) {
		return nil, errors.New("date_format_error")
	}
	// 按天选择不能超过90天
	if style == "day" && beginTime.AddDate(0, 0, 90).Before(endTime) {
		return nil, errors.New("date_format_error")
	}
	// 按周选择不能超过50周
	if style == "week" && beginTime.AddDate(0, 0, 50*7).Before(endTime) {
		return nil, errors.New("date_format_error")
	}
	// 按月选择不能超过10年
	if style == "month" && beginTime.AddDate(10, 0, 0).Before(endTime) {
		return nil, errors.New("date_format_error")
	}
	// 按周选择 第一天必须是周一 最后一天必须是周日
	if style == "week" && (beginTime.Weekday() != time.Weekday(1) || endTime.Weekday() != time.Weekday(0)) {
		return nil, errors.New("date_format_error")
	}
	// 按月选择 第一天必须是一号 最后一天必须是月末
	if style == "month" && (beginTime.Day() != 1 || endTime.AddDate(0, 0, 1).Day() != 1) {
		return nil, errors.New("date_format_error")
	}
	return []time.Time{beginTime, endTime.Add(time.Hour * 24)}, nil
}
